from odoo import fields, models, api
from odoo.exceptions import UserError, ValidationError
from datetime import time


class RPBookTime(models.Model):
    _name = 'rp.book.time'
    _description = '预约时段'

    name = fields.Char(string='名称', compute='_depends_fulfill_name', store=True)
    start_hour = fields.Integer(string='开始小时', default=0, required=True)
    start_minute = fields.Integer(string='开始分钟', default=0, required=True)
    end_hour = fields.Integer(string='结束小时', default=0, required=True)
    end_minute = fields.Integer(string='结束分钟', default=0, required=True)

    @api.depends('start_hour', 'start_minute', 'end_hour', 'end_minute')
    def _depends_fulfill_name(self):
        for s in self:
            start_hour = str(s.start_hour).zfill(2) if s.start_hour else '00'
            start_minute = str(s.start_minute).zfill(2) if s.start_minute else '00'
            end_hour = str(s.end_hour).zfill(2) if s.end_hour else '00'
            end_minute = str(s.end_minute).zfill(2) if s.end_minute else '00'
            name = '{}:{} ~ {}:{}'.format(start_hour, start_minute, end_hour, end_minute)
            s.write({'name': name})

    @api.constrains('start_hour', 'start_minute', 'end_hour', 'end_minute')
    def _check_info(self):
        for s in self:
            if not 0 <= s.start_hour <= 24:
                raise UserError('小时输入必须大于等于0，小于等于24')
            if not 0 <= s.start_hour <= 24:
                raise UserError('小时输入必须大于等于0，小于等于24')
            if not 0 <= s.start_minute <= 60:
                raise UserError('分钟输入必须大于等于0，小于等于24')
            if not 0 <= s.end_minute <= 60:
                raise UserError('分钟输入必须大于等于0，小于等于24')

    @api.constrains('start_hour', 'start_minute', 'end_hour', 'end_minute')
    def _check_time_overlap(self):
        for record in self:
            start_time = time(record.start_hour, record.start_minute)
            end_time = time(record.end_hour, record.end_minute)

            if end_time <= start_time:
                raise ValidationError("结束时间必须大于开始时间。")

            # 检查与其他记录的时间范围是否重叠
            other_records = self.search([('id', '!=', record.id)])
            for other in other_records:
                other_start = time(other.start_hour, other.start_minute)
                other_end = time(other.end_hour, other.end_minute)
                if (start_time < other_end and end_time > other_start) or (end_time > other_start and start_time < other_end):
                    raise ValidationError("时间范围重叠。")
